import Vue from 'vue'
import Vuex from 'vuex'
import {getMenus} from "@/api/system/menu";
import Layout from '@/layout'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    menus: []
  },
  getters: {
    menus: state => state.menus
  },
  mutations: {
    SET_MENUS: (state, data) => state.menus = data
  },
  actions: {
    GenerateRoutes({commit}) {
      return new Promise(resolve => {
        getMenus().then(res => {
          let userMenus = filterTreeMenus(res.data);
          commit('SET_MENUS', userMenus)
          // 深克隆数组，分离菜单和路由
          let rawRoutes = JSON.parse(JSON.stringify(userMenus));
          // 叶子节点添加路由
          let accessedRoutes = createRoute(rawRoutes);
          // accessedRoutes = filterAsyncRouter(accessedRoutes)
          accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
          resolve(accessedRoutes)
        })
      })
    }
  },

  modules: {
  }
})

/**
 * 过滤不需要生成路由的菜单项
 * 此处过滤掉隐藏属性的菜单（主要是按钮类型/功能型的）
 * @param data
 * @param arr
 * @returns {*}
 */
function filterTreeMenus(data, arr = []) {
  for(let item of data) {
    if(!item.hidden) {
      // 如果满足条件时，用新node代替，然后把chilren清空
      let node = {...item, children: []}
      arr.push(node)
      if(item.children && item.children.length > 0) {
        filterTreeMenus(item.children, node.children)
      }
    }
  }
  return arr;
}
// 叶子节点绑定路由
function createRoute(data, routes = []) {
  for(let item of data) {
      if(item.children && item.children.length > 0) {
        createRoute(item.children, routes)
      } else {
        let route = {path: item.apiUrl}
        route.children = [{path: '', name: item.title, component: loadView(item.component)}]
        route.component = Layout
        routes.push(route)
      }
  }
  return routes
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) =>  require([`@/views/${view}`], resolve)
}